import {uploadFile} from "./utils.js"

function getFileList() {
    $.ajax({
        url: "http://www.woniu-news.com:8082/getFileList.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                let content = ""
                for (let item of resp.data) {
                    content += `<li>
                            <div class='file-name'><img src="${item['file_url']}" width="50" alt="美女图片"></div>
                            <div class='file-size'>${item['file_size']}</div>
                            <div class='file-type'>${item['file_type']}</div>
                            <div class='file-actions'>
                                <a href="${item['file_url']}" download class='download'>下载</a>
                                <a href='javascript:void(0)' data-id="${item['file_url']}" class='copy'>复制地址</a>
                                <a href='javascript:void(0)' data-id="${item['file_url']}" class='delete'>删除</a>
                            </div>
                        </li>`
                }
                $(".file-list").html(content);
            }
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}

function deleteByName(url) {
    $.ajax({
        url: "http://www.woniu-news.com:8082/deleteFile.php",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        data: {
            url: url
        },
        dataType: "json",
        success: (resp) => {
            if (resp.code === 200) {
                alert(resp.message)
                getFileList()
            } else {
                alert(resp.message)
            }
        },
        error: (resp) => {
            alert(resp.message)
        }
    })
}

function copyUrl(text) {
    // 传统方法：使用 textarea 和 execCommand
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed'
    textArea.style.opacity = '0'
    document.body.appendChild(textArea)
    textArea.select()

    try {
        return document.execCommand('copy');
    } catch (err) {
        console.error('传统复制方法也失败:', err);
        return false
    } finally {
        document.body.removeChild(textArea);
    }
}

getFileList()
// 上传文件
$(".upload").click(() => {
    const file = $(".file")
    uploadFile(file).then(() => {
        getFileList()
    })
})

// 复制文件地址
$(document).on("click", ".copy", function () {
    const url = $(this).data("id")
    copyUrl(url)
})

// 删除文件事件监听
$(document).on("click", ".delete", function () {
    const url = $(this).data("id")
    deleteByName(url)
})